package com.ctshk.rpc.order.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.goods.dto.CommodityDTO;
import com.ctshk.rpc.goods.req.conmodity.CommodityAttributeReq;
import com.ctshk.rpc.goods.req.conmodity.CommodityCostReq;
import com.ctshk.rpc.goods.req.conmodity.CommodityCostSingleReq;
import com.ctshk.rpc.goods.service.ICommodityService;
import com.ctshk.rpc.order.goods.dto.CurrentUsreCartInfoDTO;
import com.ctshk.rpc.order.goods.entity.CommodityAttribute;
import com.ctshk.rpc.order.goods.entity.OrderConsigneeInfo;
import com.ctshk.rpc.order.goods.entity.ShoppingCart;
import com.ctshk.rpc.order.goods.mapper.CommodityAttributeMapper;
import com.ctshk.rpc.order.goods.mapper.OrderConsigneeInfoMapper;
import com.ctshk.rpc.order.goods.mapper.ShoppingCartMapper;
import com.ctshk.rpc.order.goods.req.OrderConsigneeInfoReq;
import com.ctshk.rpc.order.goods.req.ShoppingCartAddReq;
import com.ctshk.rpc.order.goods.req.ShoppingCartReq;
import com.ctshk.rpc.order.goods.service.IShoppingCartService;
import com.ctshk.rpc.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author 姜斌文
 * @since 2021-04-19
 */
@Slf4j
@DubboService
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {
    @DubboReference
    private ICommodityService commodityService;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private CommodityAttributeMapper commodityAttributeMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate; // redis操作类

    @Autowired
    private OrderConsigneeInfoMapper orderConsigneeInfoMapper;

    @DubboReference
    private IUserService iUserService;

    /**
     * redis中是否存在key
     *
     * @param key
     * @return
     */
    private boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addPcShoppingCart(ShoppingCartAddReq addReq, Long userId) {
        log.info("【中旅商城--APP添加商品到购物车--start】，ShoppingCartAddReq入参为:{},userId:{}", JSON.toJSONString(addReq), userId);
        checkAddCartParam(addReq);
        LocalDateTime now = LocalDateTime.now();
        ShoppingCart shoppingCart = new ShoppingCart();
        Long id = SnowflakeIdWorker.nextId();

        // 根据商品id查询商品明细
        Result<CommodityDTO> commodity = commodityService.findCommodityById(addReq.getCommodityId());
        log.info("【中旅商城--APP添加商品到购物车--查询商品明细】，返参为：{}", JSON.toJSONString(commodity));
        if (commodity.getCode() == 0 && commodity.getMsg().equalsIgnoreCase("成功")) {
            CommodityDTO commodityDTO = commodity.getData(); // 商品详细信息
            // 拿到商品成本信息
            List<CommodityCostSingleReq> commodityCostSingleReqList = commodityDTO.getCommodityCostReqList();
            log.info("【中旅商城--APP添加商品到购物车--查询商品成本】，返参为：{}", JSON.toJSONString(commodityCostSingleReqList));
            CommodityAttributeReq attributeReq = commodityDTO.getCommodityAttributeReq();
            // 判断商品是否存在,且规格相等
            log.info("【中旅商城--APP添加商品到购物车--查询购物车】，入参为：id:{},attrId:{},userId:{}", addReq.getCommodityId(), addReq.getCommodityCostAttributeId(), userId);
            List<ShoppingCart> sc = new ArrayList<>();
            if (null != addReq.getCommodityCostAttributeId() && addReq.getCommodityCostAttributeId().longValue() != addReq.getCommodityId().longValue()) {
                sc = shoppingCartMapper.selectByCommodityIdAndCommodityCostAttributeId(addReq.getCommodityId(), addReq.getCommodityCostAttributeId(), userId);
            } else {
                sc = shoppingCartMapper.selectByCommodityIdAndUserId(addReq.getCommodityId(), userId);
            }
            log.info("【中旅商城--APP添加商品到购物车--查询购物车】，返参为：{}", JSON.toJSONString(sc));
            // 数据不存在
            if (CollectionUtils.isEmpty(sc) && sc.size() <= 0) {
                // 判断商品是否单规格
                if (attributeReq.getSpecificationsType().intValue() == 1) {
                    // 商品状态:1：有效; 2：已失效
                    shoppingCart.setId(id);
                    shoppingCart.setCommodityStatus(1);
                    shoppingCart.setCommodityId(commodityDTO.getId());
                    shoppingCart.setCommodityName(commodityDTO.getCommodityName());
                    shoppingCart.setCreateId(addReq.getUserId());
                    shoppingCart.setGmtCreate(now);
                    shoppingCart.setUserId(addReq.getUserId());
                    shoppingCart.setType(addReq.getType());
                    shoppingCart.setNumber(addReq.getNumber());
                    shoppingCart.setCommodityPrice(addReq.getCommodityPrice());
                    shoppingCart.setCommodityPictureUrl(addReq.getCommodityPictureUrl());
                    shoppingCart.setSourceId(addReq.getSourceId());
                    shoppingCart.setSourceName(addReq.getSourceName());
                    shoppingCart.setCommodityName(addReq.getCommodityName());
                    shoppingCart.setCommodityNumber(addReq.getCommodityNumber());
                    shoppingCart.setModifiedId(addReq.getUserId());
                    shoppingCart.setGmtModified(now);
                    shoppingCart.setIsDeleted(IsDeletedCode.NO.getCode());
                    shoppingCart.setPlatformCode(Integer.parseInt(addReq.getCode()));
//                    shoppingCart.setCommodityCostAttributeId(addReq.getCommodityCostAttributeId());
                    shoppingCart.setCommodityCostAttributeName(addReq.getCommodityCostAttributeName());
                    shoppingCart.setMarkingPrice(addReq.getCommodityPrice());
                    log.info("【中旅商城--APP添加商品到购物车--单规格--新增购物车】，入参为：{}", JSON.toJSONString(shoppingCart));
                    shoppingCartMapper.insertCart(shoppingCart);
                    return;
                } else {
                    for (CommodityCostSingleReq commodityCostSingleReq : commodityCostSingleReqList) {
                        if (commodityCostSingleReq.getCostAttributeId().longValue() == addReq.getCommodityCostAttributeId().longValue()) {
                            if (commodityCostSingleReq.getStock() <= 0 || commodityCostSingleReq.getStock() < addReq.getNumber()) {
                                throw new BusinessException(SystemError.MALL_MERCHANDISE_23001);
                            }
                            BeanUtils.copyProperties(addReq, shoppingCart);
                            // 商品状态:1：有效; 2：已失效
                            shoppingCart.setId(id);
                            shoppingCart.setCommodityStatus(1);
                            shoppingCart.setCommodityId(commodityDTO.getId());
                            shoppingCart.setCommodityName(commodityDTO.getCommodityName());
                            shoppingCart.setCreateId(addReq.getUserId());
                            shoppingCart.setGmtCreate(now);
                            shoppingCart.setUserId(addReq.getUserId());
                            shoppingCart.setType(addReq.getType());
                            shoppingCart.setNumber(addReq.getNumber());
                            shoppingCart.setSourceId(addReq.getSourceId());
                            shoppingCart.setSourceName(addReq.getSourceName());
                            shoppingCart.setCommodityPrice(addReq.getCommodityPrice());
                            shoppingCart.setCommodityPictureUrl(addReq.getCommodityPictureUrl());
                            shoppingCart.setCommodityName(addReq.getCommodityName());
                            shoppingCart.setModifiedId(addReq.getUserId());
                            shoppingCart.setGmtModified(now);
                            shoppingCart.setCommodityNumber(addReq.getCommodityNumber());
                            shoppingCart.setIsDeleted(IsDeletedCode.NO.getCode());
                            shoppingCart.setPlatformCode(Integer.parseInt(addReq.getCode()));
                            shoppingCart.setCommodityCostAttributeId(addReq.getCommodityCostAttributeId());
                            shoppingCart.setCommodityCostAttributeName(addReq.getCommodityCostAttributeName());
                            shoppingCart.setMarkingPrice(addReq.getMarkingPrice());
                            log.info("【中旅商城--APP添加商品到购物车--多规格--新增购物车】，入参为：{}", JSON.toJSONString(shoppingCart));
                            shoppingCartMapper.insertCart(shoppingCart);
                        }
                    }
                    return;
                }
            }

            // 用户id查询购物车信息
            List<ShoppingCart> dbShoppingCart = shoppingCartMapper.findShoppingCartByUserId(userId);
            if (null != dbShoppingCart && dbShoppingCart.size() > 0) {
                for (ShoppingCart dbCart : dbShoppingCart) {
                    if (addReq.getCommodityId().longValue() == dbCart.getCommodityId().longValue()) {
                        // 判断商品是否单规格
                        if (attributeReq.getSpecificationsType().intValue() == 1) {
                            // 不为空更新数据库购物车
//                            if (null != dbCart.getCommodityCostAttributeId() && dbCart.getCommodityCostAttributeId().longValue() == addReq.getCommodityCostAttributeId().longValue()) {
                            CommodityCostReq commodityCostReq = commodityDTO.getCommodityCostReq();
                            // 成本信息设置
//                            if (commodityCostReq.getCommodityAttributeId().longValue() == addReq.getCommodityCostId().longValue()) {
                            // 库存判断
                            if (commodityCostReq.getStock() <= 0 || commodityCostReq.getStock() < dbCart.getNumber()) {
                                throw new BusinessException(SystemError.MALL_MERCHANDISE_23001);
                            }
                            // 商品有效
                            dbCart.setCommodityStatus(1);
                            dbCart.setCommodityId(commodityDTO.getId());
                            dbCart.setCommodityName(commodityDTO.getCommodityName());
                            dbCart.setModifiedId(null);
                            dbCart.setGmtModified(now);
                            dbCart.setUserId(addReq.getUserId());
                            dbCart.setCreateId(addReq.getUserId());
                            dbCart.setIsDeleted(IsDeletedCode.NO.getCode());
                            // 商品数量设置
                            int number = dbCart.getNumber() + addReq.getNumber();
                            dbCart.setNumber(number);
//                            }
                            log.info("【中旅商城--APP添加商品到购物车--单规格--更新购物车】，入参为：{}", JSON.toJSONString(dbCart));
                            shoppingCartMapper.updateCartById(dbCart);
                            return;
//                            }
                            // 多规格
                        } else {
                            if (dbCart.getCommodityCostAttributeId().longValue() == addReq.getCommodityCostAttributeId().longValue()) {
                                updateCartShoppingNumber(dbCart, addReq, commodityDTO, commodityCostSingleReqList, userId, now);
                            }
                        }
                    }
                }
            }
        } else {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23002);
        }
        log.info("【中旅商城--APP添加商品到购物车】---------end");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addShoppingCart(ShoppingCartAddReq addReq, Long userId) {
        checkAddCartParam(addReq);
        LocalDateTime now = LocalDateTime.now();
        ShoppingCart shoppingCart = new ShoppingCart();
        // 根据商品id查询商品明细
        Result<CommodityDTO> commodity = commodityService.findCommodityById(addReq.getCommodityId());
        if (commodity.getCode() == 0 && commodity.getMsg().equalsIgnoreCase("成功")) {
            CommodityDTO commodityDTO = commodity.getData(); // 商品详细信息
            // 用户id查询购物车信息
            List<ShoppingCart> dbShoppingCart = shoppingCartMapper.findShoppingCartByUserId(userId);
            CommodityAttributeReq attributeReq = commodityDTO.getCommodityAttributeReq();
            if (attributeReq == null) {
                CommodityAttribute commodityAttribute = commodityAttributeMapper.findCommodityAttributeByCommodityId(commodityDTO.getId());
                if (commodityAttribute != null) {
                    attributeReq = new CommodityAttributeReq();
                    BeanUtils.copyProperties(commodityAttribute, attributeReq);
                }
            }
            // 拿到商品成本信息
            List<CommodityCostSingleReq> commodityCostSingleReqList = commodityDTO.getCommodityCostReqList();
            // 单规格
            if (attributeReq != null) {
                if (attributeReq.getSpecificationsType() == 1) {
                    for (ShoppingCart dbCart : dbShoppingCart) {
                        if (addReq.getCommodityId().longValue() == dbCart.getCommodityId().longValue()) {
                            if (null == dbCart.getCommodityCostAttributeId() && null == addReq.getCommodityCostAttributeId()) {
                                // 更新购物车数量
                                updateCartShoppingNumber(dbCart, addReq, commodityDTO, commodityCostSingleReqList, userId, now);
                                return;
                            } else {
                                if (null != addReq.getCommodityCostAttributeId() &&
                                        dbCart.getCommodityCostAttributeId().longValue() == addReq.getCommodityCostAttributeId().longValue()) {
                                    updateCartShoppingNumber(dbCart, addReq, commodityDTO, commodityCostSingleReqList, userId, now);
                                    return;
                                }
                            }
                        }
                    }
                    // 多规格
                } else {
                    if (commodityCostSingleReqList != null) {
                        for (CommodityCostSingleReq commodityCostSingleReq : commodityCostSingleReqList) {
                            if (commodityCostSingleReq.getStock() <= 0 || commodityCostSingleReq.getStock() < addReq.getNumber()) {
                                throw new BusinessException(SystemError.MALL_MERCHANDISE_23001);
                            }
                            BeanUtils.copyProperties(addReq, shoppingCart);
                            // 商品状态:1：有效; 2：已失效
                            shoppingCart.setCommodityStatus(1);
                            shoppingCart.setCommodityId(commodityDTO.getId());
                            shoppingCart.setCommodityName(commodityDTO.getCommodityName());
                            shoppingCart.setCreateId(userId);
                            shoppingCart.setGmtCreate(now);
                            shoppingCart.setModifiedId(userId);
                            shoppingCart.setGmtModified(now);
                            shoppingCart.setIsDeleted(IsDeletedCode.NO.getCode());
                            shoppingCartMapper.insert(shoppingCart);
                            break;
                        }
                    }
                }
            }
        } else {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23002);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delAppShoppingCart(List<Long> ids, Long userId) {
        log.info("【中旅商城--app删除购物车--start】,入参为ids:{},userId:{}", JSON.toJSONString(ids), userId);
        if (null == userId) {
            throw new BusinessException(SystemError.SYS_406);
        }
        shoppingCartMapper.deleteCartByIds(ids);
        log.info("【中旅商城--app删除购物车--end】");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateShoppingCartNumber(JSONObject req, Long userId) {
        log.info("【中旅商城--APP更新商品数量--start】,req入参为:{},userId:{}", JSON.toJSONString(req), userId);
        if (null == userId) {
            throw new BusinessException(SystemError.SYS_406);
        }
        if (null == req || "{}".equalsIgnoreCase(req.toString())) {
            throw new BusinessException(SystemError.SYS_402);
        }
        Long id = req.getLong("id");
        Integer number = req.getInteger("number");
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setId(id);
        shoppingCart.setNumber(number);
        shoppingCart.setGmtModified(LocalDateTime.now());
        shoppingCart.setModifiedId(userId);
        shoppingCartMapper.updateCartInfoById(shoppingCart);

        log.info("【中旅商城--APP更新商品数量--end】");
    }

    @Override
    public List<CurrentUsreCartInfoDTO> findCurrentUsreCartInfoList(Long userId) {
        List<CurrentUsreCartInfoDTO> resultCartDTO = new ArrayList<>();
        // 登录态判断
        if (null == userId) {
            throw new BusinessException(SystemError.SYS_406);
        }
        // 查询购物车列表
        List<ShoppingCart> dbCurrentCart = shoppingCartMapper.findShoppingCartByUserId(userId);
        if (null == dbCurrentCart || dbCurrentCart.size() == 0) {
            return resultCartDTO;
        }
        // 购物车总价
        BigDecimal currentUserCartTotalPrice = new BigDecimal(0);
        for (ShoppingCart dbCart : dbCurrentCart) {
            LocalDateTime now = LocalDateTime.now();
            CurrentUsreCartInfoDTO cartInfoDTO = new CurrentUsreCartInfoDTO();
            // 根据商品ID查询明细
            Result<CommodityDTO> dbCommodity = commodityService.findCommodityById(dbCart.getCommodityId());
            if (dbCommodity.getCode() == 0 && dbCommodity.getMsg().equalsIgnoreCase("成功")) {
                CommodityDTO commodityDTO = dbCommodity.getData(); // 商品详细信息
                List<CommodityCostSingleReq> commodityCostSingleReqList = commodityDTO.getCommodityCostReqList(); // 商品成本
                if (commodityCostSingleReqList != null) {
                    // 根据商品id对集合分组
                    Map<Long, List<CommodityCostSingleReq>> costGroup = commodityCostSingleReqList.stream()
                            .collect(Collectors.groupingBy(CommodityCostSingleReq::getCommodityId));
                    // 拿到商品成本
                    List<CommodityCostSingleReq> costSingleReqList = costGroup.get(dbCart.getCommodityId());
                    if (null != costSingleReqList && costSingleReqList.size() > 0) {
                        for (CommodityCostSingleReq costSingleReq : costSingleReqList) {
                            // 商品单价
                            BigDecimal singleShoppingPrice = new BigDecimal(0);
                            if (null == dbCart.getCommodityCostAttributeId() && null == costSingleReq.getCostAttributeId()) {
                                BeanUtils.copyProperties(dbCart, cartInfoDTO);
                                // 库存判断
                                if (costSingleReq.getStock() <= 0 || costSingleReq.getStock() < cartInfoDTO.getNumber()) {
                                    cartInfoDTO.setSkuIsSufficient("N");
                                }
                                cartInfoDTO.setCommodityPrice(new BigDecimal(costSingleReq.getPrice().toString()));
                                singleShoppingPrice.add(cartInfoDTO.getCommodityPrice());
                                singleShoppingPrice = singleShoppingPrice.multiply(new BigDecimal(cartInfoDTO.getNumber()));
                                currentUserCartTotalPrice = currentUserCartTotalPrice.add(singleShoppingPrice);
                                resultCartDTO.add(cartInfoDTO);
                                break;
                            } else {
                                BeanUtils.copyProperties(dbCart, cartInfoDTO);
                                // 库存判断
                                if (costSingleReq.getStock() <= 0 || costSingleReq.getStock() < cartInfoDTO.getNumber()) {
                                    cartInfoDTO.setSkuIsSufficient("N");
                                    break;
                                }
                                cartInfoDTO.setCommodityPrice(new BigDecimal(costSingleReq.getCostPrice().toString()));
                                BigDecimal price = new BigDecimal(cartInfoDTO.getCommodityPrice().toString());
                                singleShoppingPrice = singleShoppingPrice.add(price);
                                BigDecimal number = new BigDecimal(cartInfoDTO.getNumber().toString());
                                singleShoppingPrice = singleShoppingPrice.multiply(number);
                                currentUserCartTotalPrice = currentUserCartTotalPrice.add(singleShoppingPrice);
                                resultCartDTO.add(cartInfoDTO);
                                break;
                            }
                        }
                    }
                }
            }
        }
        if (CollectionUtils.isNotEmpty(resultCartDTO)) {
            for (CurrentUsreCartInfoDTO currentUsreCartInfoDTO : resultCartDTO) {
                currentUsreCartInfoDTO.setCurrentUserCartTotalPrice(currentUserCartTotalPrice);
            }
        }
        return resultCartDTO;
    }

    @Override
    public List<CurrentUsreCartInfoDTO> findPcCurrentUsreCartInfoList(Long userId, Integer code) {
        log.info("【中旅商城--APP购物车列表获取--start】,入参为code:{},userId:{}", code, userId);
        List<CurrentUsreCartInfoDTO> resultCartDTO = new ArrayList<>();
        // 登录态判断
        if (null == userId) {
            throw new BusinessException(SystemError.SYS_406);
        }

        LocalDateTime currentNow = LocalDateTime.now();
//        LocalDateTime backTime = null;
        // 时间比较策略
//        if (hasKey(RedisConstants.GOODS_COMMODITY_TIME_CART)) {
//            backTime = JSON.parseObject(redisTemplate.opsForValue().get(RedisConstants.GOODS_COMMODITY_TIME_CART), LocalDateTime.class);
//        }
//        boolean before = backTime.isBefore(currentNow);
//        if (!before) {
//            // 存储最新时间
//            redisTemplate.opsForValue().set(RedisConstants.GOODS_COMMODITY_TIME_CART, JSON.toJSONString(currentNow));
//        }

        getNow(currentNow);
        // 缓存有数据获取
        if (hasKey(RedisConstants.GOODS_COMMODITY_CART + ":" + userId)) {
            // 购物车总价
            BigDecimal currentUserCartTotalPrice = new BigDecimal(0);
            // 查询购物车列表
            List<ShoppingCart> dbCurrentCart = shoppingCartMapper.findPcShoppingCartByUserId(userId, code, currentNow);
            List<CurrentUsreCartInfoDTO> currentUsreCartInfoDTOS = new ArrayList<>();
            // 缓存数据
            currentUsreCartInfoDTOS = JSON.parseArray(redisTemplate.opsForValue().get(RedisConstants.GOODS_COMMODITY_CART), CurrentUsreCartInfoDTO.class);
            if (null == dbCurrentCart || dbCurrentCart.size() == 0 && null != currentUsreCartInfoDTOS) {
                return currentUsreCartInfoDTOS;
            }
            if (CollectionUtils.isNotEmpty(currentUsreCartInfoDTOS)) {
                List<CurrentUsreCartInfoDTO> resultCartDTOs = new ArrayList<>();
                resultCartDTOs = buildShoppingCart(dbCurrentCart, userId, currentUserCartTotalPrice, resultCartDTO);
                currentUsreCartInfoDTOS.addAll(resultCartDTOs);
                redisTemplate.opsForValue().set(RedisConstants.GOODS_COMMODITY_CART + ":" + userId, JSON.toJSONString(currentUsreCartInfoDTOS));
            }
            return currentUsreCartInfoDTOS;
            // 缓存无数据获取
        } else {
            // 查询购物车列表
            List<ShoppingCart> dbCurrentCart = shoppingCartMapper.findPcShoppingCartByUserId(userId, code, null);
            if (null == dbCurrentCart || dbCurrentCart.size() == 0) {
                return resultCartDTO;
            }
            // 购物车总价
            BigDecimal currentUserCartTotalPrice = new BigDecimal(0);
            resultCartDTO = buildShoppingCart(dbCurrentCart, userId, currentUserCartTotalPrice, resultCartDTO);
            if (CollectionUtils.isNotEmpty(resultCartDTO)) {
                for (CurrentUsreCartInfoDTO currentUsreCartInfoDTO : resultCartDTO) {
                    if (currentUsreCartInfoDTO.getNumber() != 0) {
                        currentUserCartTotalPrice = currentUserCartTotalPrice.add(currentUsreCartInfoDTO.getCommodityPrice().divide(new BigDecimal(currentUsreCartInfoDTO.getNumber()), BigDecimal.ROUND_HALF_UP));
                    }
                    currentUsreCartInfoDTO.setCurrentUserCartTotalPrice(currentUserCartTotalPrice);
                }
            }
        }
//        redisTemplate.opsForValue().set(RedisConstants.GOODS_COMMODITY_CART + ":" + userId, JSON.toJSONString(resultCartDTO));
        log.info("【中旅商城--APP购物车列表获取--end】");
        return resultCartDTO;
    }

    /**
     * 购物车信息查询构建
     *
     * @param dbCurrentCart
     * @param userId
     * @param currentUserCartTotalPrice
     * @param resultCartDTO
     * @return
     */
    public List<CurrentUsreCartInfoDTO> buildShoppingCart(List<ShoppingCart> dbCurrentCart, Long
            userId, BigDecimal currentUserCartTotalPrice, List<CurrentUsreCartInfoDTO> resultCartDTO) {

        for (ShoppingCart dbCart : dbCurrentCart) {
            LocalDateTime now = LocalDateTime.now();
            CurrentUsreCartInfoDTO cartInfoDTO = new CurrentUsreCartInfoDTO();
            // 根据商品ID查询明细
            Result<CommodityDTO> dbCommodity = commodityService.findCommodityById(dbCart.getCommodityId());
            if (dbCommodity.getCode() == 0 && dbCommodity.getMsg().equalsIgnoreCase("成功")) {
                CommodityDTO commodityDTO = dbCommodity.getData(); // 商品详细信息
                CommodityAttributeReq attributeReq = commodityDTO.getCommodityAttributeReq();
                // 单规格
                if (attributeReq.getSpecificationsType() == 1) {
                    CommodityCostReq commodityCostReq = commodityDTO.getCommodityCostReq();
                    if (null != commodityCostReq) {
                        // 商品单价
                        BigDecimal singleShoppingPrice = new BigDecimal(0);
                        if (null == dbCart.getCommodityCostAttributeId() && null == commodityCostReq.getCommodityAttributeId()) {
                            BeanUtils.copyProperties(dbCart, cartInfoDTO);
                            // 库存判断
                            if (commodityCostReq.getStock() <= 0 || commodityCostReq.getStock() < cartInfoDTO.getNumber()) {
                                cartInfoDTO.setNumber(0);
                                cartInfoDTO.setSkuIsSufficient("N");
                            }
                            cartInfoDTO.setCommodityPrice(new BigDecimal(commodityCostReq.getCostPrice().toString()));
                            singleShoppingPrice.add(cartInfoDTO.getCommodityPrice());
                            singleShoppingPrice = singleShoppingPrice.multiply(new BigDecimal(cartInfoDTO.getNumber()));
                            currentUserCartTotalPrice = currentUserCartTotalPrice.add(singleShoppingPrice);
                            resultCartDTO.add(cartInfoDTO);
//                            break;
                        } else {
//                            if (dbCart.getCommodityCostAttributeId().longValue() == commodityCostReq.getCostAttributeId().longValue()) {
                            BeanUtils.copyProperties(dbCart, cartInfoDTO);
                            // 库存判断
                            if (commodityCostReq.getStock() <= 0 || commodityCostReq.getStock() < cartInfoDTO.getNumber()) {
                                cartInfoDTO.setSkuIsSufficient("N");
                                cartInfoDTO.setNumber(0);
//                                break;
                            }
                            cartInfoDTO.setCommodityPrice(new BigDecimal(commodityCostReq.getCostPrice().toString()));
                            BigDecimal price = new BigDecimal(cartInfoDTO.getCommodityPrice().toString());
                            singleShoppingPrice = singleShoppingPrice.add(price);
                            BigDecimal number = new BigDecimal(cartInfoDTO.getNumber().toString());
                            singleShoppingPrice = singleShoppingPrice.multiply(number);
                            currentUserCartTotalPrice = currentUserCartTotalPrice.add(singleShoppingPrice);
                            resultCartDTO.add(cartInfoDTO);
//                                break;
//                            }
                        }
                    }
                    // 多规格
                } else if (attributeReq.getSpecificationsType() == 2) {
                    List<CommodityCostSingleReq> commodityCostSingleReqList = commodityDTO.getCommodityCostReqList(); // 商品成本
                    if (CollectionUtils.isNotEmpty(commodityCostSingleReqList)) {
                        // 根据商品id对集合分组
                        Map<Long, List<CommodityCostSingleReq>> costGroup = commodityCostSingleReqList.stream()
                                .collect(Collectors.groupingBy(CommodityCostSingleReq::getCommodityId));
                        // 拿到商品成本
                        List<CommodityCostSingleReq> costSingleReqList = costGroup.get(dbCart.getCommodityId());
                        if (null != costSingleReqList && costSingleReqList.size() > 0) {
                            for (CommodityCostSingleReq costSingleReq : costSingleReqList) {
                                // 商品单价
                                BigDecimal singleShoppingPrice = new BigDecimal(0);
                                if (null == dbCart.getCommodityCostAttributeId() && null == costSingleReq.getCommodityAttributeId()) {
                                    BeanUtils.copyProperties(dbCart, cartInfoDTO);
                                    // 库存判断
                                    if (costSingleReq.getStock() <= 0 || costSingleReq.getStock() < cartInfoDTO.getNumber()) {
                                        cartInfoDTO.setNumber(0);
                                        cartInfoDTO.setSkuIsSufficient("N");
                                    }
                                    cartInfoDTO.setCommodityPrice(new BigDecimal(costSingleReq.getCostPrice().toString()));
                                    singleShoppingPrice.add(cartInfoDTO.getCommodityPrice());
                                    singleShoppingPrice = singleShoppingPrice.multiply(new BigDecimal(cartInfoDTO.getNumber()));
                                    currentUserCartTotalPrice = currentUserCartTotalPrice.add(singleShoppingPrice);
                                    resultCartDTO.add(cartInfoDTO);
//                                    break;
                                }
                                else {
                                    if (null != dbCart.getCommodityCostAttributeId() && dbCart.getCommodityCostAttributeId().longValue() == costSingleReq.getCostAttributeId().longValue()) {
                                        BeanUtils.copyProperties(dbCart, cartInfoDTO);
                                        // 库存判断
                                        if (costSingleReq.getStock() <= 0 || costSingleReq.getStock() < cartInfoDTO.getNumber()) {
                                            cartInfoDTO.setNumber(0);
                                            cartInfoDTO.setSkuIsSufficient("N");
//                                            break;
                                        }
                                        cartInfoDTO.setCommodityPrice(new BigDecimal(costSingleReq.getCostPrice().toString()));
                                        BigDecimal price = new BigDecimal(cartInfoDTO.getCommodityPrice().toString());
                                        singleShoppingPrice = singleShoppingPrice.add(price);
                                        BigDecimal number = new BigDecimal(cartInfoDTO.getNumber().toString());
                                        singleShoppingPrice = singleShoppingPrice.multiply(number);
                                        currentUserCartTotalPrice = currentUserCartTotalPrice.add(singleShoppingPrice);
                                        resultCartDTO.add(cartInfoDTO);
//                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

            }
        }
        return resultCartDTO;
    }

    @Override
    public Result<PageResponse<ShoppingCartReq>> findUserShoppingCarInfoByLogout(String code, Integer from, Integer
            size) {
        log.info("【中旅商城--查询购物车列表--start】，入参为 -- code:{},from:{},size:{}", code, from, size);
        if (from == null || size == null) {
            from = 1;
            size = 10;
        }
        boolean bool = hasKey(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + code);
        // 根据标识获取
        if (bool) {
            List<ShoppingCartReq> cartReqs = JSON.parseArray(redisTemplate.opsForValue().get(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + code), ShoppingCartReq.class);
            log.info("【中旅商城--查询购物车列表--缓存查询】，返参为 ：{}", cartReqs);
//            for (ShoppingCartReq cartReq : cartReqs) {
//                List<ShoppingSpecialPageUrlDTO> list = JSON.parseArray(cartReq.getCommodityPictureUrl(), ShoppingSpecialPageUrlDTO.class);
//                cartReq.setCommodityPictureUrl(list.get(0).getUrl());
//            }
            IPage<ShoppingCartReq> shoppingCartReqIPage = new Page<>(from, size);
            PageResponse<ShoppingCartReq> result = new PageResponse<>(cartReqs, shoppingCartReqIPage.getCurrent() == 1, cartReqs.size() <= (shoppingCartReqIPage.getCurrent() * shoppingCartReqIPage.getSize()), cartReqs.size(), shoppingCartReqIPage.getCurrent(), shoppingCartReqIPage.getSize());
            return Result.success(result);
        }
        log.info("【中旅商城--查询购物车列表--end】");
        return Result.failed(SystemError.MALL_MERCHANDISE_23012);
    }

    /**
     * 更新策略，获取缓存中上次存储的时间点
     *
     * @param now
     * @return
     */
    private LocalDateTime getNow(LocalDateTime now) {
        // 获取缓存中时间点
        String key = redisTemplate.opsForValue().get(RedisConstants.GOODS_COMMODITY_TIME_CART);
        boolean flag = hasKey(RedisConstants.GOODS_COMMODITY_TIME_CART);
        if (flag) {
            LocalDateTime time = JSON.parseObject(key, LocalDateTime.class);
            if (!now.isBefore(time)) {
                now = time;
            }
            redisTemplate.opsForValue().set(RedisConstants.GOODS_COMMODITY_TIME_CART, JSON.toJSONString(now));
        }
        return now;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addShoppingCartByLogout(ShoppingCartAddReq addReq) {
        log.info("【中旅商城--添加商品到购物车--未登录--start】，入参为:{}", JSON.toJSONString(addReq));
        List<ShoppingCart> carts = new ArrayList<>();
        // 参数校验
        checkAddCartParam(addReq);
        LocalDateTime now = LocalDateTime.now();
        ShoppingCart shoppingCart = new ShoppingCart();

//        LocalDateTime currentNow = getNow(now);

        // 根据商品id查询商品明细
        Result<CommodityDTO> commodity = commodityService.findCommodityById(addReq.getCommodityId());
        log.info("【中旅商城--添加商品到购物车--未登录--查询商品明细】，返参为:{}", JSON.toJSONString(commodity));
        if (commodity.getCode() == 0 && commodity.getMsg().equalsIgnoreCase("成功")) {
            //商品详细信息
            CommodityDTO commodityDTO = commodity.getData();
            // 缓存查询购物车信息
            if (hasKey(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + addReq.getCode())) {
                List<ShoppingCart> cartReqs = JSON.parseArray(redisTemplate.opsForValue().get(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + addReq.getCode()), ShoppingCart.class);
                log.info("【中旅商城--添加商品到购物车--未登录--查询购物车列表】，返参为:{}", JSON.toJSONString(cartReqs));
                boolean isTrue = false;
                // 新增的商品和查询的商品不是同一个，标识为TRUE
                boolean flage = false;
                CommodityAttribute byCommodityId = commodityAttributeMapper.findCommodityAttributeByCommodityId(addReq.getCommodityId());
                for (ShoppingCart cartReq : cartReqs) {
                    if (cartReq.getCommodityId().equals(addReq.getCommodityId())) {
                        if (byCommodityId.getSpecificationsType().intValue() == 1) { //单规格
                            isTrue = true;
//                            flage = true;
                        } else if (byCommodityId.getSpecificationsType().intValue() == 2) { // 多规格
                            // 标识该商品已经存在购物车
                            if (cartReq.getCommodityId().equals(addReq.getCommodityId()) && cartReq.getCommodityCostAttributeId().equals(addReq.getCommodityCostAttributeId())) {
                                isTrue = true;
                            }
                            if (
                                // 商品不同、属性不同
                                    (!cartReq.getCommodityId().equals(addReq.getCommodityId()) && (!cartReq.getCommodityCostAttributeId().equals(addReq.getCommodityCostAttributeId()))) ||
                                            // 商品相同、属性不同
                                            (cartReq.getCommodityId().equals(addReq.getCommodityId()) && (!cartReq.getCommodityCostAttributeId().equals(addReq.getCommodityCostAttributeId()))) ||
                                            // 商品不同、属性相同
                                            ((!cartReq.getCommodityId().equals(addReq.getCommodityId())) && cartReq.getCommodityCostAttributeId().equals(addReq.getCommodityCostAttributeId()))
                            ) {
                                flage = true;
                            }
                        }
                    } else {
                        flage = true;
                    }
                }
                CommodityAttributeReq attributeReq = commodityDTO.getCommodityAttributeReq();
                for (ShoppingCart cartReq : cartReqs) {

                    // 更新购物车
                    if (isTrue) {
//                        ShoppingCart shoppingCart1 = new ShoppingCart();
                        if (addReq.getCommodityId().longValue() == cartReq.getCommodityId().longValue()) {
                            //单规格
                            if (attributeReq.getSpecificationsType().intValue() == 1) {
                                CommodityCostReq commodityCostReq = commodityDTO.getCommodityCostReq();
                                // 成本信息设置
//                            if (commodityCostReq.getId().longValue() == addReq.getCommodityCostId().longValue()) {
                                // 库存判断
                                if (commodityCostReq.getStock() <= 0 || commodityCostReq.getStock() < cartReq.getNumber()) {
                                    throw new BusinessException(SystemError.MALL_MERCHANDISE_23001);
                                }
                                // 商品有效
                                shoppingCart.setCommodityStatus(1);
                                shoppingCart.setCommodityId(commodityDTO.getId());
                                shoppingCart.setCommodityName(commodityDTO.getCommodityName());
                                shoppingCart.setModifiedId(null);
                                shoppingCart.setGmtModified(now);
                                shoppingCart.setCommodityCostAttributeId(addReq.getCommodityId());
                                shoppingCart.setCommodityCostAttributeName(addReq.getCommodityCostAttributeName());
                                shoppingCart.setSourceName(addReq.getSourceName());
                                shoppingCart.setSourceId(addReq.getSourceId());
                                shoppingCart.setCommodityName(addReq.getCommodityName());
                                shoppingCart.setCommodityPrice(addReq.getCommodityPrice());
                                shoppingCart.setCommodityPictureUrl(addReq.getCommodityPictureUrl());
                                shoppingCart.setCommodityStatus(addReq.getCommodityStatus());
                                shoppingCart.setIsDeleted(IsDeletedCode.NO.getCode());
                                shoppingCart.setMarkingPrice(addReq.getMarkingPrice());
                                // 商品数量设置
                                int number = cartReq.getNumber() + addReq.getNumber();
                                shoppingCart.setNumber(number);
//                                // 保存已添加的对象
                                carts.add(shoppingCart);
                                break;
//                            }
                            } else { //多规格
                                //拿到商品成本信息
                                List<CommodityCostSingleReq> commodityCostReqList = commodityDTO.getCommodityCostReqList();
                                // 更新购物车数量
                                ShoppingCart cart = updateCacheCartShoppingNumber(cartReq, addReq, commodityDTO, commodityCostReqList, now);
                                // 相同则覆盖
                                if (cart.getCommodityId().longValue() == cartReq.getCommodityId().longValue()) {
                                    shoppingCart = EntityUtil.copy(cart, ShoppingCart.class);
                                }
                                // 保存已添加的对象
                                carts.add(shoppingCart);
                                break;
                            }
                        }
                        // 新增购物车
                    } else if (flage) {
                        // 同件商品、不同规格
                        //单规格
                        if (attributeReq.getSpecificationsType().intValue() == 1) {
                            CommodityCostReq commodityCostReq = commodityDTO.getCommodityCostReq();
                            // 成本信息设置
//                            if (commodityCostReq.getId().longValue() == addReq.getCommodityCostId().longValue()) {
                            // 库存判断
                            if (commodityCostReq.getStock() <= 0 || commodityCostReq.getStock() < cartReq.getNumber()) {
                                throw new BusinessException(SystemError.MALL_MERCHANDISE_23001);
                            }
                            // 商品有效
                            shoppingCart.setCommodityStatus(1);
                            shoppingCart.setCommodityId(commodityDTO.getId());
                            shoppingCart.setCommodityName(commodityDTO.getCommodityName());
                            shoppingCart.setModifiedId(null);
                            shoppingCart.setGmtModified(now);
                            shoppingCart.setCommodityCostAttributeId(addReq.getCommodityId());
                            shoppingCart.setCommodityCostAttributeName(addReq.getCommodityCostAttributeName());
                            shoppingCart.setSourceName(addReq.getSourceName());
                            shoppingCart.setSourceId(addReq.getSourceId());
                            shoppingCart.setCommodityName(addReq.getCommodityName());
                            shoppingCart.setCommodityPrice(addReq.getCommodityPrice());
                            shoppingCart.setCommodityPictureUrl(addReq.getCommodityPictureUrl());
                            shoppingCart.setCommodityStatus(addReq.getCommodityStatus());
                            shoppingCart.setIsDeleted(IsDeletedCode.NO.getCode());
                            shoppingCart.setMarkingPrice(addReq.getMarkingPrice());
                            // 商品数量设置
                            shoppingCart.setNumber(addReq.getNumber());
                            // 保存已添加的对象
                            carts.add(shoppingCart);
                            break;
                        } else { //多规格
                            // 拿到商品成本信息
                            List<CommodityCostSingleReq> commodityCostReqList = commodityDTO.getCommodityCostReqList();
//                            if (cartReq.getCommodityId().longValue() != cartReq.getCommodityCostAttributeId().longValue()) {
                            // 更新购物车数量
//                            ShoppingCart cart = updateCacheCartShoppingNumber(cartReq, addReq, commodityDTO, commodityCostReqList, now);
//                            // 相同则覆盖
//                            if (cart.getCommodityId().longValue() == cartReq.getCommodityId().longValue()) {
//                                shoppingCart = EntityUtil.copy(cart, ShoppingCart.class);
//                            }
//                            // 保存已添加的对象
//                            carts.add(shoppingCart);
                            // 商品有效
                            shoppingCart.setCommodityStatus(1);
                            shoppingCart.setCommodityId(commodityDTO.getId());
                            shoppingCart.setCommodityName(commodityDTO.getCommodityName());
                            shoppingCart.setModifiedId(null);
                            shoppingCart.setGmtModified(now);
                            shoppingCart.setCommodityCostAttributeId(addReq.getCommodityCostAttributeId());
                            shoppingCart.setCommodityCostAttributeName(addReq.getCommodityCostAttributeName());
                            shoppingCart.setSourceName(addReq.getSourceName());
                            shoppingCart.setSourceId(addReq.getSourceId());
                            shoppingCart.setCommodityName(addReq.getCommodityName());
                            shoppingCart.setCommodityPrice(addReq.getCommodityPrice());
                            shoppingCart.setCommodityPictureUrl(addReq.getCommodityPictureUrl());
                            shoppingCart.setCommodityStatus(addReq.getCommodityStatus());
                            shoppingCart.setIsDeleted(IsDeletedCode.NO.getCode());
                            shoppingCart.setMarkingPrice(addReq.getMarkingPrice());
                            // 商品数量设置
                            shoppingCart.setNumber(addReq.getNumber());
                            // 保存已添加的对象
                            carts.add(shoppingCart);
                            break;
                        }
//                        }
                    }
                }
//                if (!isTrue) {
                // 保存已添加的对象并过滤
                carts.addAll(cartReqs);
                carts = carts.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ShoppingCart::getCommodityCostAttributeId))), ArrayList::new));
//                }
            } else {
                // 缓存中没有购物车列表
                shoppingCart = EntityUtil.copy(addReq, ShoppingCart.class);
                shoppingCart.setCommodityCostAttributeId(addReq.getCommodityId());
                carts.add(shoppingCart);
            }
            log.info("【中旅商城--添加商品到购物车--未登录--添加购物车到缓存】，入参为：{}", JSON.toJSONString(carts));
            redisTemplate.delete(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + addReq.getCode());
            redisTemplate.opsForValue().set(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + addReq.getCode(), JSON.toJSONString(carts), 86400, TimeUnit.MINUTES);
            log.info("【中旅商城--添加商品到购物车--未登录--end】");
            return;
        } else {
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23012);
        }
    }

    /**
     * 校驗加入購物車商品入參基本參數
     *
     * @param shoppingCartReqs
     */
    private void checkAddCartParams(List<ShoppingCartReq> shoppingCartReqs) {
        if (CollectionUtils.isEmpty(shoppingCartReqs)) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (null == shoppingCartReqs || shoppingCartReqs.stream().filter(req -> {
            return req.getCommodityId() == null;
        }).collect(Collectors.toList()).size() > 0) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (shoppingCartReqs.stream().filter(req -> {
            return req.getNumber() == null;
        }).collect(Collectors.toList()).size() > 0 || shoppingCartReqs.stream().filter(req -> {
            return req.getNumber() <= 0;
        }).collect(Collectors.toList()).size() > 0) {
            throw new BusinessException(SystemError.SYS_402);
        }
    }

    @Override
    public Result upAddress(OrderConsigneeInfoReq orderConsigneeInfoReq) {
        // 查询对应订单的地址信息
        Long orderId = orderConsigneeInfoReq.getOrderId();
        if (orderId == null) {
            return Result.failed(SystemError.GOODS_ORDER_ERROR_40007);
        }
        OrderConsigneeInfo infoByOrder = orderConsigneeInfoMapper.findConsigneeInfoByOrder(orderId);
        if (infoByOrder == null) {
            return Result.failed(SystemError.GOODS_ORDER_ERROR_40008);
        }
        infoByOrder = EntityUtil.copy(orderConsigneeInfoReq, OrderConsigneeInfo.class);
        orderConsigneeInfoMapper.updateById(infoByOrder);
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateShoppingCartNumberByLogout(JSONObject req) {
        log.info("【中旅商城--更新购物车--未登录--start】,入参为：{}", JSON.toJSONString(req));
        if (null == req || "{}".equalsIgnoreCase(req.toString())) {
            throw new BusinessException(SystemError.SYS_402);
        }
        Long id = req.getLong("id");
        Long costId = req.getLong("costId");
        String code = req.getString("code");
        Integer number = req.getInteger("number");
//        ShoppingCart shoppingCart = new ShoppingCart();
//        shoppingCart.setId(id);
//        shoppingCart.setNumber(number);
//        shoppingCart.setGmtModified(LocalDateTime.now());
//        shoppingCart.setModifiedId(userId);
        // 存在缓存
        if (hasKey(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + code)) {
            List<ShoppingCart> cartList = new ArrayList<>();
            List<ShoppingCart> carts = JSON.parseArray(redisTemplate.opsForValue().get(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + code), ShoppingCart.class);
            log.info("【中旅商城--更新购物车--未登录--查询购物车】,返参为：{}", JSON.toJSONString(carts));
            CommodityAttribute attributeByCommodityId = commodityAttributeMapper.findCommodityAttributeByCommodityId(id);
            for (ShoppingCart cart : carts) {
                if (attributeByCommodityId.getSpecificationsType().intValue() == 1) { // 单规格
                    if (cart.getCommodityId().longValue() == id) {
//                    cart = EntityUtil.copy(shoppingCart, ShoppingCart.class);
                        cart.setNumber(number);
//                        cart.setCommodityCostAttributeId(cart.getCommodityId());
                        cart.setGmtModified(LocalDateTime.now());
                        cartList.add(cart);
                    }
                } else if (attributeByCommodityId.getSpecificationsType().intValue() == 2) { // 多规格
                    if (cart.getCommodityId().longValue() == id && cart.getCommodityCostAttributeId().longValue() == costId) {
//                    cart = EntityUtil.copy(shoppingCart, ShoppingCart.class);
                        cart.setNumber(number);
                        cart.setGmtModified(LocalDateTime.now());
                        cartList.add(cart);
                    }
                }
            }
            carts.addAll(cartList);
            carts = carts.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ShoppingCart::getCommodityCostAttributeId))), ArrayList::new));
            log.info("【中旅商城--更新购物车--未登录--新增购物车】,入参为：{}", JSON.toJSONString(carts));
            redisTemplate.opsForValue().set(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + code, JSON.toJSONString(carts), 86400, TimeUnit.MINUTES);
        }
        log.info("【中旅商城--更新购物车--未登录--end】");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delShoppingCartByLogout(JSONObject req) {
        log.info("【中旅商城--app删除购物车--未登录--start】，入参为:{}", JSON.toJSONString(req));
        if (null == req || "{}".equalsIgnoreCase(req.toString())) {
            throw new BusinessException(SystemError.SYS_402);
        }
        JSONArray shoppingCart = req.getJSONArray("shoppingCart");
        String code = req.get("code").toString();
        for (int i = 0; i < shoppingCart.size(); i++) {
            Map map = (LinkedHashMap) shoppingCart.get(i);
            Long commodityId = Long.parseLong(map.get("id").toString());
            Long costId = Long.parseLong(map.get("costId").toString());
            if (hasKey(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + code)) {
                List<ShoppingCart> carts = JSON.parseArray(redisTemplate.opsForValue().get(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + code), ShoppingCart.class);
                log.info("【中旅商城--app删除购物车--未登录--缓存购物车列表查询】，返参为:{}", JSON.toJSONString(carts));
                List<ShoppingCart> collect = new ArrayList<>();
                // 购物车不为空更新操作
//                if (CollectionUtils.isNotEmpty(carts)) {
                for (ShoppingCart cart : carts) {
                    boolean isExist = false;
                    if (cart.getCommodityId().longValue() == commodityId
                            && cart.getCommodityCostAttributeId().longValue() == costId) {
                        isExist = true;
//                        continue;
                    }
                    // 不存在cart中，则添加
                    if (!isExist) {
                        collect.add(cart);
                    }
                }
                redisTemplate.delete(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + code);
                if (collect.size() >= 1) {
                    log.info("【中旅商城--app删除购物车--未登录--新增购物车】，重载redis入参:{}", JSON.toJSONString(collect));
                    redisTemplate.opsForValue().set(RedisConstants.GOODS_COMMODITY_LOGOUT_CART + ":" + code, JSON.toJSONString(collect), 10, TimeUnit.MINUTES);
                }
//                }

            }
        }
        log.info("【中旅商城--app删除购物车--未登录--end】");
    }

    /**
     * 更新购物车数量
     *
     * @param dbCart
     * @param addReq
     * @param commodityDTO
     * @param commodityCostSingleReqList
     * @param userId
     * @param now
     */
    private void updateCartShoppingNumber(ShoppingCart dbCart, ShoppingCartAddReq addReq, CommodityDTO
            commodityDTO,
                                          List<CommodityCostSingleReq> commodityCostSingleReqList, Long userId, LocalDateTime now) {
        // 商品数量设置
        dbCart.setNumber(dbCart.getNumber() + addReq.getNumber());
        // 成本信息设置
        for (CommodityCostSingleReq commodityCostSingleReq : commodityCostSingleReqList) {
            if (commodityCostSingleReq.getCommodityAttributeId().longValue() == addReq.getCommodityCostAttributeId().longValue()) {
                // 库存判断
                if (commodityCostSingleReq.getStock() <= 0 || commodityCostSingleReq.getStock() < dbCart.getNumber()) {
                    throw new BusinessException(SystemError.MALL_MERCHANDISE_23001);
                }
                // 商品有效
                dbCart.setCommodityStatus(1);
                dbCart.setCommodityId(commodityDTO.getId());
                dbCart.setCommodityName(commodityDTO.getCommodityName());
                dbCart.setModifiedId(userId);
                dbCart.setGmtModified(now);
                dbCart.setIsDeleted(IsDeletedCode.NO.getCode());
                break;
            }
        }
        shoppingCartMapper.updateCartById(dbCart);
    }

    /**
     * 更新缓存购物车数量
     *
     * @param dbCart
     * @param addReq
     * @param commodityDTO
     * @param commodityCostSingleReqList
     * @param now
     */
    private ShoppingCart updateCacheCartShoppingNumber(ShoppingCart dbCart, ShoppingCartAddReq addReq, CommodityDTO
            commodityDTO,
                                                       List<CommodityCostSingleReq> commodityCostSingleReqList, LocalDateTime now) {
        // 商品数量设置
        dbCart.setNumber(dbCart.getNumber() + addReq.getNumber());
        // 成本信息设置
        for (CommodityCostSingleReq commodityCostSingleReq : commodityCostSingleReqList) {
            if (commodityCostSingleReq.getCommodityAttributeId().longValue() == addReq.getCommodityCostAttributeId().longValue()) {
                // 库存判断
                if (commodityCostSingleReq.getStock() <= 0 || commodityCostSingleReq.getStock() < dbCart.getNumber()) {
                    throw new BusinessException(SystemError.MALL_MERCHANDISE_23001);
                }
                // 商品有效
                dbCart.setCommodityStatus(1);
                dbCart.setCommodityId(commodityDTO.getId());
                dbCart.setCommodityName(commodityDTO.getCommodityName());
                dbCart.setModifiedId(null);
                dbCart.setGmtModified(now);
                dbCart.setIsDeleted(IsDeletedCode.NO.getCode());
                break;
            }
        }
        return dbCart;
    }

    /**
     * 校驗加入購物車商品入參基本參數
     *
     * @param addReq 購物車入參
     * @throws Exception 異常
     */
    private void checkAddCartParam(ShoppingCartAddReq addReq) {
        if (null == addReq || null == addReq.getCommodityId()) {
            throw new BusinessException(SystemError.SYS_402);
        }
        if (null == addReq.getNumber() || addReq.getNumber() <= 0) {
            throw new BusinessException(SystemError.SYS_402);
        }
    }
}
